package com.axend.lib_base.help

import android.text.format.DateUtils
import androidx.annotation.MainThread

class CountdownHelper(
    private val durationInMillis: Long,
    private val onCountdownFinishedListener: OnCountdownFinishedListener?
) {

    private var timeLeftInMillis: Long = durationInMillis
    private var countdownTimer: CountDownTimer? = null

    interface OnCountdownFinishedListener {
        fun onCountdownFinished()
        fun onCountdownTick(time: String)
    }

    @MainThread
    fun startCountdown() {
        if (countdownTimer != null) {
            countdownTimer?.cancel()
        }
        countdownTimer = object : CountDownTimer(timeLeftInMillis, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                timeLeftInMillis = millisUntilFinished
                updateCountdownText()
            }

            override fun onFinish() {
                onCountdownFinishedListener?.onCountdownFinished()
                countdownTimer = null
            }
        }.start() as CountDownTimer?
    }

    private fun updateCountdownText() {
        val minutes = timeLeftInMillis / DateUtils.MINUTE_IN_MILLIS
        val seconds = (timeLeftInMillis % DateUtils.MINUTE_IN_MILLIS) / DateUtils.SECOND_IN_MILLIS
        val timeFormatted = String.format("%02d", seconds)
        // 更新UI，这里需要传递给外部的TextView或其他UI组件
        // 示例：updateTextView(timeFormatted)
        onCountdownFinishedListener?.onCountdownTick(timeFormatted)
    }

    @MainThread
    fun cancelCountdown() {
        countdownTimer?.cancel()
        countdownTimer = null
    }
}

// 内部类 CountDownTimer
private open class CountDownTimer(
    private val millisInFuture: Long,
    private val countDownInterval: Long
) : android.os.CountDownTimer(millisInFuture, countDownInterval) {
    override fun onTick(millisUntilFinished: Long) {
        // 实现内部计时逻辑
    }

    override fun onFinish() {
        // 实现计时结束逻辑
    }
}